package com.bolehui.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bolehui.base.result.Result;
import com.bolehui.base.utils.StringUtils;
import com.bolehui.domain.dto.CompanyDTO;
import com.bolehui.domain.po.CompanyPO;
import com.bolehui.domain.po.SysDictData;
import com.bolehui.domain.vo.CompanyVO;
import com.bolehui.mapper.AreaMapper;
import com.bolehui.mapper.CompanyMapper;
import com.bolehui.mapper.SysDictDataMapper;
import com.bolehui.service.CompanyService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author chendongjie     email:chendongjie@gz.iscas.ac.cn
 * @version 1.0
 * @ClassName CompanyService
 * @Description
 * @createTime 2025/3/7-14:53
 * Copyright (C) 2021-2022 CASEEDER, All Rights Reserved.
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 */
@Service
public class CompanyServiceImpl extends ServiceImpl<CompanyMapper, CompanyPO> implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private SysDictDataMapper sysDictDataMapper;

    @Override
    public Result saveOrUpdate(CompanyVO company, Long userId) {
        CompanyPO companyPO = companyMapper.selectByUserId(userId);
        if(ObjectUtil.isNull(companyPO)){
            CompanyPO companyInfo = new CompanyPO();
            BeanUtils.copyProperties(company, companyInfo);
            companyMapper.insert(companyInfo);
        }

        BeanUtils.copyProperties(company, companyPO);
        companyPO.setUserId(userId);
        companyMapper.updateById(companyPO);
        return Result.success();
    }
    @Override
    public CompanyDTO selectByUserId(Long userId) {
        // 查询数据库
        CompanyPO company = companyMapper.selectByUserId(userId);

        // 如果查询结果为空，返回 null
        if (company == null) {
            return null;
        }

        // 将 Company 实体转换为 CompanyDTO
        CompanyDTO companyDTO = new CompanyDTO();
        BeanUtils.copyProperties(company, companyDTO); // 使用 Spring 的 BeanUtils 复制属性
        String areaCode = company.getAreaCode();
        String allLabel = areaMapper.getAreaByCode(areaCode);
        if(StringUtils.isNotEmpty(allLabel)){
            companyDTO.setAllLabel(allLabel);
        }

        int label = company.getLabel();
        SysDictData sysDictData = sysDictDataMapper.selectById(label);

        String dictLabel = sysDictData.getDictLabel();
        if(ObjectUtil.isNotNull(dictLabel)){
            companyDTO.setLabel(dictLabel);
        }
        return companyDTO;
    }


}
